#!/usr/bin/env python2
#-*- coding: utf-8 -*-
"""
Created on 20151124
"""


import json

from Ump.umptypes import UmpPath
from message_mapping import InstanceMap, method_map


class MessageHandler:

    def __init__(self):
        self.instance_map = InstanceMap()
    
    def analyse_msg(self, msg):
        if not isinstance(msg,dict):
            msg = json.loads(msg)

        msg_body = msg.values()[0]
        operation = msg.keys()[0]

        operation = method_map.get(operation, '').split('.')
        operation = [x for x in operation if x]

        if not operation:
            raise Exception('invalid operation')          

        instance = operation[0]
        method = operation[1]
        params = msg_body.get('params', {})
        params = self.wrapper_path_from_params(params, instance, method)

        owner = params.get('owner')
        if owner:
            params['username'] = owner

        instanceClass = getattr(self.instance_map, instance)
        method = getattr(instanceClass, method)
        setattr(instanceClass, 'cls', None)
        return method(params)
    
    def wrapper_path_from_params(self, params, instance, method):
        if instance in ['pool', 'volume', 'snapshot'] and method in ['create', 'clone', 'copy']:
            protocol = params['protocol']
            username = params.get('username', 'admin')

            protocol2 = params.get('protocol2')

            name = params.get('name')

            for field in ['protocol', 'username', 'name']:
                params.pop(field, None)

            params['path'] = UmpPath(name, protocol=protocol, username=username)
            owner = params.get('owner')
            if owner:
                params['path'] = UmpPath(name, protocol=protocol, username=owner)

            name2 = params.pop('name2', None)
            owner2 = params.get('owner2')
            if name2:
                params['path2'] = UmpPath(name2, protocol=protocol, username=username)

            if name2 and owner2 and protocol2:
                params['path2'] = UmpPath(name2, protocol=protocol2, username=owner2)
        return params
